# coding=utf-8
from selenium import webdriver
import json
import time
import re
from selenium.webdriver.chrome.options import Options
from conf import setting
from base import authcode_mode
import requests
import os
requests.packages.urllib3.disable_warnings()


class GetHeaders:

    # 设置浏览器日志参数
    caps = {'browserName': 'chrome',
            'loggingPrefs': {
                'browser': 'ALL',
                'driver': 'ALL',
                'performance': 'ALL', },
            'goog:chromeOptions': {
                'perfLoggingPrefs': {'enableNetwork': True,},
                'w3c': False,},
            }

    def __init__(self):
        self.header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
            'Cookie': '',
        }
        self.proxies = {'https': 'https://127.0.0.1:12759'}
        chrome_options = Options()
        # 忽略https安全访问问题
        chrome_options.add_argument('--ignore-certificate-errors')
        # 无头模式
        if setting.HEADLESS:
            chrome_options.add_argument('--headless')
            chrome_options.add_argument('--disable-gpu')
            chrome_options.add_experimental_option('w3c', False)
            self.driver = webdriver.Chrome(desired_capabilities=self.caps, options=chrome_options)
        else:
            self.driver = webdriver.Chrome(options=chrome_options)

    def login(self):
        self.driver.get(setting.URL)
        time.sleep(2)
        cookie = [item["name"] + "=" + item["value"] for item in self.driver.get_cookies()]
        self.header['Cookie'] = '; '.join(cookie)
        count = 0
        while True:
            try:
                # 用户名
                self.driver.find_element_by_xpath(setting.NAME_ELE).clear()
                self.driver.find_element_by_xpath(setting.NAME_ELE).send_keys(setting.NAME)
                # 密码
                self.driver.find_element_by_xpath(setting.PASSWORD_ELE).clear()
                self.driver.find_element_by_xpath(setting.PASSWORD_ELE).send_keys(setting.PASSWORD)
                # 下载验证码
                self.download_jpg()
                # 识别验证码
                code = authcode_mode.predict_one(setting.CODE_PATH)
                self.driver.find_element_by_xpath(setting.AUTHCODE_ELE).clear()
                self.driver.find_element_by_xpath(setting.AUTHCODE_ELE).send_keys(code)
                time.sleep(1.5)
                self.driver.find_element_by_xpath(setting.LOGIN_BUTTON_ELE).click()
                # 断言是否登录成功
                assert  setting.NAME in self.driver.find_element_by_xpath(setting.LOGIN_NAME_ELE).text
            except Exception as e:
                count += 1
                if count < setting.LOGIN_COUNT:
                    print('验证码识别登录失败,失败次数{},尝试重新登录……\n失败信息:\n{}'.format(count,traceback.print_exc()))
                    # 这里需要进行刷新操作，不然页面会有异常
                    self.driver.refresh()
                    time.sleep(3)
                    continue
                else:
                    print '已超过最大次数{}，程序终止'.format(setting.LOGIN_COUNT)
                    break
            else:
                print('验证码识别登录成功……[ {} ]'.format(code))
                time.sleep(2)
                break

    def download_jpg(self,n=1):
        res = requests.get(setting.CODE_URL, headers=self.header, proxies=self.proxies, verify=False)
        if res:
            path = 'authcode'
            if not os.path.exists(path):
                os.makedirs(path)
            file_path = os.path.join(os.getcwd(), path)
            self.save_jpg(res.content, file_path + '\\' + 'test' + '.jpg')
        else:
            print('获取验证码失败')

    def save_jpg(self,data, file_path):
        with open(file_path, 'wb') as fp:
            fp.write(data)

    def write_header(self, head, code=None, filetype='json'):
        if filetype == 'json':
            with open('header.json', 'w', encoding='utf-8') as fp:
                msg = {"header": head, "code": code}
                fp.write(json.dumps(msg, ensure_ascii=False))
        elif filetype == 'txt':
            with open('header.txt', 'w', encoding='utf-8') as fx:
                for i in head.keys():
                    fx.write(i+': '+head[i] + '\n')
        else:
            print("不支持该类型")
            return None

    def get_cookie_demo(self):
        self.login()
        self.driver.find_element_by_xpath('//*[contains(text(),"任务调度")]').click()
        time.sleep(3)
        listCookies = self.driver.get_cookies()
        cookie = [item["name"] + "=" + item["value"] for item in listCookies]
        self.header['Cookie'] = '; '.join(cookie)
        print 'Cookie信息: {}'.format(self.header['Cookie'])
        # 测试demo,尝试访问任务调度的查询接口
        res1 = requests.get('https://'+setting.IP+':8080/tdw/guldan/api/taskScheduler/folder/find?keyword=', headers=self.header, proxies=self.proxies, verify=False)
        res2 = requests.get('https://'+setting.IP+'/api/multi/cluster/manager/list?isValid=1',
                           headers=self.header, proxies=self.proxies, verify=False)
        res3 = requests.get('https://'+setting.IP+'/api/project/queryAllProjectsInfo?pageSize=10&pageIndex=0&name=',
                            headers=self.header, proxies=self.proxies, verify=False)
        # print('任务调度>>> ',res1.text)
        # print('运维中心>>> ',res2.text)
        # print('平台管理>>> ',res3.text)

    def  get_ti_cookie(self):
        self.login()
        self.driver.find_element_by_xpath('//*[contains(text(),"机器学习")]').click()
        time.sleep(3)
        listCookies = self.driver.get_cookies()
        cookie = [item["name"] + "=" + item["value"] for item in listCookies]
        self.header['Cookie'] = '; '.join(cookie)
        res = requests.get('https://'+setting.IP+':8080/tdw/serving/api/model/list?appId=1&modelType=PRIVATE&requestId=1594784406610&withVersions=true&size=20&orderBy=created&desc=true&type=filter&queryByName=&userId=',
                            headers=self.header, proxies=self.proxies, verify=False)
        # print('机器学习>>> ',res.text)
        # return cookie

    def get_datamanager_cookie(self):
        self.login()
        self.driver.find_element_by_xpath('//*[contains(text(),"数据管理")]').click()
        time.sleep(3)
        listCookies = self.driver.get_cookies()
        cookie = [item["name"] + "=" + item["value"] for item in listCookies]
        self.header['Cookie'] = '; '.join(cookie)
        res = requests.get(
            'https://'+setting.IP+':8080/tdw/uther/api/tables/listManageTables?tableType=&projectId=&clusterId=&dbName=&size=10&page=0',
            headers=self.header, proxies=self.proxies, verify=False)
        # print('数据管理>>> ',res.text)

if __name__ == '__main__':
    hd = GetHeaders()
    # 获取数据管理cookie
    hd.get_cookie_demo()
    # hd.get_yunwei_cookie()

